import axios from 'axios'
import qs from 'qs'
import { clearEmptyParam } from '@/utils/lib/object'
import { HttpCode, LangApiHeader } from '@/enums'
import { useAccountStore, useAppStore } from '@/store'
import { ResType } from '@/types'

declare module 'axios' {
	interface AxiosInstance {
		(config: AxiosRequestConfig): Promise<any>
	}
}

const service = axios.create({
	baseURL: import.meta.env.VITE_BASE_API,
	timeout: 1000 * 60,
	withCredentials: true
})

// request interceptor
service.interceptors.request.use(
	(config: any) => {
		// do something before request is sent
		const accountStore = useAccountStore()
		const appStore = useAppStore()
		const defaultHeaders = <Record<string, string>>{
			lang: LangApiHeader[appStore.lang]
		}
		if (accountStore.token) {
			defaultHeaders.authorization = `Bearer ${accountStore.token}`
		}
		if (config.method.toLowerCase() === 'get' && config.params) {
			config.url =
				config.url + '?' + qs.stringify(clearEmptyParam(config.params), { indices: false })
			config.params = null
		}
		config.headers = { ...defaultHeaders, ...config.headers }
		return config
	},
	(error) => {
		// do something with request error
		return Promise.reject(error)
	}
)

// 响应拦截器
service.interceptors.response.use(
	(response: any) => {
		if (response.data instanceof Blob) {
			return response.data
		}
		const { code, msg, data } = response.data
		//   要根据success的成功与否决定下面的操作
		const resData: ResType = { data, code, msg }
		if (code === HttpCode.Success || code === HttpCode.GamesSuccess) {
			return resData
		} else {
			console.debug(response.config.url, resData)
			if (code === HttpCode.TokenError || code === HttpCode.NoLoginError) {
				// TODO 应该给个提示 登录过期之类的,然后让用户重新登录
				const accountStore = useAccountStore()
				accountStore.clearLoginInfo()
			} else if (code === HttpCode.UserForbiddenError) {
				// store.commit('user/forbidden')
			} else if (!Object.values(HttpCode).includes(code)) {
				// 	resData.code = HttpCode.Unknown
			}
			return Promise.reject(resData)
		}
	},
	(err) => {
		// const resData: ResType = {
		// 	code: HttpCode.Network,
		// 	data: response.data
		// }
		return Promise.reject(err.response.data)
	}
)

export default service
